<template>
  <div class="login-container">
    <div class="login-form">
      <h2>登录系统</h2>
      <div class="form-group">
        <label for="username">用户名</label>
        <input
          type="text"
          id="username"
          v-model="username"
          placeholder="请输入用户名"
          :class="{ 'error': errorMsg }"
        />
      </div>
      <div class="form-group">
        <label for="password">密码</label>
        <input
          type="password"
          id="password"
          v-model="password"
          placeholder="请输入密码"
          :class="{ 'error': errorMsg }"
        />
      </div>
      <div v-if="errorMsg" class="error-message">{{ errorMsg }}</div>
      <button @click="handleLogin" :disabled="isLoading" class="login-button">
        {{ isLoading ? '登录中...' : '登录' }}
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';

const router = useRouter();
const username = ref('');
const password = ref('');
const errorMsg = ref('');
const isLoading = ref(false);

const handleLogin = async () => {
  // 重置错误信息
  errorMsg.value = '';
  
  // 简单的表单验证
  if (!username.value || !password.value) {
    errorMsg.value = '请输入用户名和密码';
    return;
  }
  
  isLoading.value = true;
  
  try {
    // 构建请求体
    const requestBody = {
      username: username.value,
      password: password.value
    };
    
    // 发送真实请求
    const response = await fetch('/api/v3/command/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(requestBody)
    });
    
    // 解析响应数据
    const data = await response.json();
    
    // 检查登录是否成功
    if (data.success && data.result === true) {
      // 保存登录状态到localStorage
      localStorage.setItem('isLoggedIn', 'true');
      localStorage.setItem('username', username.value);
      localStorage.setItem('loginTime', data.server_time);
      localStorage.setItem('requestUuid', data.request_uuid);
      
      // 登录成功后跳转到首页
      router.push('/');
    } else {
      // 登录失败，显示错误信息
      errorMsg.value = data.errors || '用户名或密码错误';
    }
  } catch (error) {
    // 处理错误，区分无网络和其他错误
    if (error.name === 'TypeError' && error.message === 'Failed to fetch') {
      // 无网络或网络连接错误
      errorMsg.value = '网络连接失败，请检查您的网络设置后重试';
    } else {
      // 其他类型的错误
      errorMsg.value = '登录失败，请稍后重试';
    }
    console.error('Login error:', error);
  } finally {
    // 无论如何都要取消加载状态
    isLoading.value = false;
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

.login-form {
  background: white;
  padding: 40px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
}

.login-form h2 {
  margin-bottom: 30px;
  text-align: center;
  color: #333;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #555;
}

.form-group input {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
  transition: border-color 0.3s;
  box-sizing: border-box;
}

.form-group input:focus {
  outline: none;
  border-color: #42b983;
}

.form-group input.error {
  border-color: #e74c3c;
}

.error-message {
  color: #e74c3c;
  margin-bottom: 20px;
  padding: 10px;
  background-color: #fdf2f2;
  border-radius: 4px;
}

.login-button {
  width: 100%;
  padding: 12px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.login-button:hover:not(:disabled) {
  background-color: #3aa876;
}

.login-button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

@media (max-width: 480px) {
  .login-form {
    padding: 20px;
  }
}
</style>